let IcyObserver = require('../observer-pattern/observer');

let Observer = new IcyObserver();
let targetObject = {};



/**
 * @function Proxy
 * @param { object } -- the target that is intercepted
 * @param { handler } -- DIY the actions while intercepted
 * @return { Proxy } -- use the constructed object as target object to make the proxy work
 */
let obj = new Proxy(
  
  // this is the target object that will be visited
  targetObject

, {
  /**
   * @function get -- call on while work as RHS
   * @param { object } target intercepted object
   * @param { object } propKey attribute name
   * @param { object } receiver this
   * @description avoid using receiver in get 
   */
  get: (target, propKey, receiver) => {
    if (propKey in target) {
      return target[propKey];
    } else {
      throw new Error(`ReferenceError: '${propKey}' is undefined!`);
    }
  },

  /**
   * @function set -- call on while work as RHS
   * @param { object } target intercepted object
   * @param { object } propKey attribute name
   * @param { any } value value of the attribute
   * @param { object } receiver this
   */
  set: (target, propKey, value, receiver) => {
    target[propKey] = value;
    Observer.publish('dataChange', value);
  }
});

// ------ TEST BEGIN ------ //

{
  let data;
  Observer.subscribe('dataChange', (value) => {
    data = value;
    console.log(`data1 => ${data}`);
  });
  Observer.subscribe('dataChange', () => {
    console.log(`data2 => ${data}`);
  });
  console.log(`data0 => ${data}`);
}

{
  obj.emit = 'send';
  obj.emit2 = 'send again';
}
// ------ TEST END ------ //
